package com.minimvc.core
{
	import flash.system.ApplicationDomain;
	import flash.utils.Dictionary;

	/**
	 * 接口对应实现类  
	 * @author crl;
	 * 
	 */	
	public class Singleton
	{
		private static var classMap:Dictionary=new Dictionary();
		private static var insMap:Dictionary=new Dictionary();
		
		/**
		 * 注册接口 实现类; 
		 * @param interfaceName 接口名称
		 * @param clazz 实现类
		 * @return 是否注册成功;
		 * 
		 */		
		public static function registerClass(interfaceName:String,clazz:Class):void{
			classMap[interfaceName] = clazz;
		}
		
		/**
		 * 取得一个实现接口的类 
		 * @param interfaceName
		 * @return 
		 * 
		 */		
		public static function getClass(interfaceName:String):Class{
			var c:Class= classMap[interfaceName] as Class;
			if(c==null){
				var domain:ApplicationDomain=ApplicationDomain.currentDomain;
				if(domain.hasDefinition(interfaceName)){
					c=domain.getDefinition(interfaceName) as Class;
				}
			}
			return c;
		}
		
		/**
		 * 取得实现接口的单例,必须含有 getInstance的静态方法;
		 * @param interfaceName 接口名称;
		 * @return 返回实现的单例
		 * 
		 */		
		public static function getInstance(interfaceName:String):*{
			var c:Class=getClass(interfaceName);
			if (!c)
			{
				throw new Error("No class registered for interface '" +
					interfaceName + "'.");
			}
			var ins:*=insMap[c];
			if(ins==null){
				insMap[c]=ins=new c();
			}
			return ins;
		}
	}
}